<script setup lang="ts">
import {
  reqAddOrUpdateUser,
  reqAllRole,
  reqRemoveUser,
  reqSelectUser,
  reqSetUserRole,
  reqUserInfo,
} from '@/apis/acl/user'
import { useLayoutSettingStore } from '@/store/modules/setting'
import type { AllRole, Records, SetRoleData, User } from '@/types/account'
import { ElMessage, type CheckboxValueType, type ElForm } from 'element-plus'
import { computed, nextTick, onMounted, ref } from 'vue'

// 当前页码
const pageNo = ref(1)
// 每页展示多少数据
const limit = ref(5)
//分页总数据
const total = ref(10)
// 关键字
const keyWord = ref('')
//存储用户信息
const userInfo = ref<Records>([])
//获取全部用户信息
const getUserInfo = async (page = 1) => {
  pageNo.value = page
  const res = await reqUserInfo(pageNo.value, limit.value, keyWord.value)
  if (res.code === 200) {
    //收集用户信息
    userInfo.value = res.data.records
    total.value = res.data.total
  }
}
//页码大小改变
const handleSizeChange = () => {
  getUserInfo()
}
//初始化调用
onMounted(() => {
  getUserInfo()
})
//控制抽屉组件的显示与开启
const drawer = ref(false)
// 控制分配角色抽屉组件的显示与隐藏
const drawerRole = ref(false)
//获取表单实例
const userformRef = ref<InstanceType<typeof ElForm>>()
//定义表单数据
const userForm = ref<User>({
  username: '',
  name: '',
  password: '',
})
//自定义表单规则
const validatorUserName = (_rule: any, value: any, callback: any) => {
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('用户名字至少5位'))
  }
}
const validatorName = (_rule: any, value: any, callback: any) => {
  if (value.length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称至少5位'))
  }
}
const validatorPassWord = (_rule: any, value: any, callback: any) => {
  if (value.length >= 6) {
    callback()
  } else {
    callback(new Error('密码至少6位'))
  }
}
//定义表单规则
const rules = computed(() => {
  const base = {
    username: [
      {
        required: true,
        min: 4,
        max: 10,
        message: '用户名长度为4到10个字符',
        trigger: 'blur',
      },
      {
        trigger: 'blur',
        validator: validatorUserName,
      },
    ],
    name: [
      {
        required: true,
        min: 4,
        max: 10,
        message: '用户名长度为4到10个字符',
        trigger: 'blur',
      },
      {
        trigger: 'blur',
        validator: validatorName,
      },
    ],
  }
  // 如果是添加用户（没有id），则添加密码规则
  if (!userForm.value.id) {
    return {
      ...base,
      password: [
        {
          required: true,
          min: 6,
          max: 15,
          message: '密码长度至少6位',
          trigger: 'blur',
        },
        {
          trigger: 'blur',
          validator: validatorPassWord,
        },
      ],
    }
  } else {
    return base
  }
})
//添加职位
const addUser = () => {
  //清空表单
  Object.assign(userForm.value, {
    username: '',
    name: '',
    password: '',
  })
  userForm.value.id = ''
  //移除表单校验
  nextTick(() => {
    userformRef.value?.clearValidate('username')
    userformRef.value?.clearValidate('name')
    userformRef.value?.clearValidate('password')
  })
  //打开弹框组件
  drawer.value = true
}
//编辑职位
const updateUser = (row: User) => {
  //移除表单校验
  nextTick(() => {
    userformRef.value?.clearValidate('username')
    userformRef.value?.clearValidate('name')
  })
  //获取表单数据
  Object.assign(userForm.value, JSON.parse(JSON.stringify(row)))
  //打开弹框组件
  drawer.value = true
}
//确定按钮回调事件
const confirm = async () => {
  //表单校验成功后
  await userformRef.value?.validate()
  //添加和修改职位
  const res = await reqAddOrUpdateUser(userForm.value)
  if (res.code === 200) {
    ElMessage.success(userForm.value.id ? '更新成功' : '添加成功')
    //关闭弹框
    drawer.value = false
    //浏览器自动刷新
    window.location.reload()
  } else {
    ElMessage.error(userForm.value.id ? '更新失败' : '添加失败')
    //关闭弹框
    drawer.value = false
  }
}
//删除职位
const deleteUser = async (id: number) => {
  const res = await reqRemoveUser(id)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    //关闭弹框
    drawer.value = false
    getUserInfo(userInfo.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage.error('删除失败')
    //关闭弹框
    drawer.value = false
  }
}
//批量删除
const selectIdArr = ref<User[]>([])
const selectChange = (val: any) => {
  selectIdArr.value = val
}
const deleteSelect = async () => {
  const idsList = selectIdArr.value.map((item) => {
    return item.id
  })
  console.log(idsList)
  const res: any = await reqSelectUser(idsList as number[])
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getUserInfo(userInfo.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage.error('删除失败')
  }
}

//存储用户所有角色
const allRole = ref<AllRole>([])
//复选框操作
const checkAll = ref(false)
const isIndeterminate = ref(true)
const userRole = ref<AllRole>([])

//分配角色
const setRole = async (row: User) => {
  //存储用户信息
  Object.assign(userForm.value, row)
  //获取全部职位和已有职位
  const res = await reqAllRole(userForm.value.id as number)
  if (res.code === 200) {
    //全部职位
    allRole.value = res.data.allRolesList
    // 已有职位
    userRole.value = res.data.assignRoles
    //打开抽屉组件
    drawerRole.value = true
  }
}
//复选框过滤
const handleCheckAllChange = (val: CheckboxValueType) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: CheckboxValueType[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length
}

//确认按钮的事件回调
const save = async () => {
  const SetRoleData = ref<SetRoleData>({
    userId: userForm.value.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  })
  const res = await reqSetUserRole(SetRoleData.value)
  if (res.code === 200) {
    //关闭抽屉组件
    drawerRole.value = false
    //提示用户
    ElMessage.success('分配角色职位成功')
    //重新获取数据
    getUserInfo(pageNo.value)
  } else {
    //关闭抽屉组件
    drawerRole.value = false
    //提示用户
    ElMessage.success('分配角色职位失败')
  }
}
//搜索
const search = () => {
  getUserInfo()
  //清空表单
  keyWord.value = ''
}
//重置
const settingStore = useLayoutSettingStore()
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
</script>

<template>
  <div>
    <!-- 顶部 -->
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名">
          <el-input placeholder="请输入用户名" v-model="keyWord"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="keyWord ? false : true"
            @click="search"
          >
            搜索
          </el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 中间内容 -->
    <el-card style="margin: 10px 0">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button
        type="danger"
        @click="deleteSelect"
        :disabled="selectIdArr.length ? false : true"
      >
        批量删除
      </el-button>
      <!-- 表格组件 -->
      <el-table
        :border="true"
        style="margin: 10px 0"
        :data="userInfo"
        @selection-change="selectChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          label="#"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="ID" align="center" prop="id"></el-table-column>
        <el-table-column
          label="用户名字"
          align="center"
          prop="name"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户名称"
          align="center"
          prop="username"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="用户角色"
          align="center"
          prop="roleName"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="User"
              @click="setRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateUser(row)"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`你确认删除${row.username}吗？`"
              width="240px"
              placement="left"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next,jumper,->,sizes,total,  "
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getUserInfo"
      />
    </el-card>
    <!-- 抽屉组件 -->
    <el-drawer v-model="drawer" :title="userForm.id ? '更新用户' : '添加用户'">
      <!-- 表单组件 -->
      <el-form :model="userForm" :rules="rules" ref="userformRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            v-model="userForm.name"
            placeholder="请输入用户昵称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userForm.id">
          <el-input
            v-model="userForm.password"
            placeholder="请输入用户密码"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
    </el-drawer>
    <!-- 分配角色抽屉组件 -->
    <el-drawer v-model="drawerRole" title="分配角色(职位)">
      <!-- 表单组件 -->
      <el-form>
        <el-form-item label="用户姓名">
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户姓名"
            clearable
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <!-- 显示职位的复选框 -->
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="index"
              :label="role"
              :value="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawerRole = false">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
